Resource leak: input is never closed

131

Resource leak: 'input' is never closed -

// You need to close Scanner. It can run, but there will be resource problems in the future.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String txt = input.nextLine();
    System.out.println("input "+txt);           
}

// Change to
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    try{
        String txt = input.nextLine();
        System.out.println("input "+txt);
    } finally {
        input.close();
    }            
}

resurce leak java -

public void readShapeData() throws IOException {
    Scanner in = new Scanner(System.in);
    try {
        System.out.println("Enter the width of the Rectangle: ");
        width = in.nextDouble();
        System.out.println("Enter the height of the Rectangle: ");
        height = in.nextDouble();
    } finally {
        in.close();
    }
}

Comments

Submit
0 Comments